/**
 * 
 */
package br.com.cept.sce.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;

import br.com.cept.sce.commons.util.DAOManager;
import br.com.cept.sce.dominio.impl.Usuario;

/**
 * @author Junier Amorim
 *
 */
public class UsuarioDAO {
	
	public Usuario carregarUsuario(String login) throws Exception{
		Usuario u = null;
		List<Usuario> resultList = null;
		EntityManager entityManager = DAOManager.getEntityManager();
		
		Query query = entityManager.createQuery("from Usuario u where u.login = :login");
		query.setParameter("login", login);
		
		resultList = query.getResultList();
		
		if(resultList.size() > 0)
			u = resultList.get(0);
		return u;
	}
	
	
	public List<Usuario> listarTodosUsuarios() throws Exception{
		Usuario u = null;
		List<Usuario> resultList = null;
		EntityManager entityManager = DAOManager.getEntityManager();
		
		Query query = entityManager.createQuery("from Usuario u order by u.nome");
		
		resultList = query.getResultList();
	
		return resultList;
	}
	
	
	public void salvar(Usuario user)throws Exception{
		EntityManager entityManager = DAOManager.getEntityManager();
		EntityTransaction transaction = entityManager.getTransaction();		
		try{
			transaction.begin();
			entityManager.persist(user);
			transaction.commit();
			entityManager.close();
		}catch(Exception erro){
			transaction.rollback();
			erro.printStackTrace();
			throw erro;
		}		
	}
	
	public void atualizar(Usuario user)throws Exception{
		EntityManager entityManager = DAOManager.getEntityManager();
		EntityTransaction transaction = entityManager.getTransaction();		
		try{
			transaction.begin();
			entityManager.merge(user);
			transaction.commit();
			entityManager.close();
		}catch(Exception erro){
			transaction.rollback();
			erro.printStackTrace();
			throw erro;
		}		
	}
	
	public void excluir(Long id)throws Exception{
		List<Usuario> resultList = null;
		EntityManager entityManager = DAOManager.getEntityManager();
		EntityTransaction transaction = entityManager.getTransaction();	
		Query query = entityManager.createQuery("delete from Usuario u where u.id = :id");
		query.setParameter("id", id);
		try{
			transaction.begin();
			query.executeUpdate();
			transaction.commit();
			entityManager.close();
		}catch(Exception erro){
			transaction.rollback();
			erro.printStackTrace();
			throw erro;
		}		
	}

}
